package top.swle.austers.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import top.swle.austers.bean.Objects;
import top.swle.austers.bean.ResponseBean;
import top.swle.austers.mapper.ObjectsMapper;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RequestMapping("/objects")
@RestController
public class LostAndFoundController {
    @Resource
    ObjectsMapper objectsMapper;

    @RequiresAuthentication
    @PostMapping("/lost")
    public ResponseBean found(@RequestPart MultipartFile file,@RequestParam(name = "objects") String objects){
        if (file.isEmpty()) {
            return new ResponseBean(-1,"文件不能为空",null);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = "/home/lostandfound/";
//        String filePath = "C:\\springboot\\lost\\";
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
            System.out.println("不存在目录");
        }
        System.out.println("objects="+objects);
        Gson gson = new Gson();
        Objects objects1 = gson.fromJson(objects,Objects.class);
        objects1.setImgaddress(filePath+fileName);
        objectsMapper.IssueLost(objects1);


        try {
            file.transferTo(dest);
            System.out.println("上传成功后的文件路径未：" + filePath + fileName);
            return new ResponseBean(1,fileName,null);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return new ResponseBean(-1,"上传失败",null);
        }
    }

    @RequiresAuthentication
    @PostMapping("/query")
    public ResponseBean query(@RequestBody Objects objects){
        List<Objects> objectsList = objectsMapper.queryAll(objects);

        Gson gson = new Gson();
        String json = gson.toJson(objectsList);
        return new ResponseBean(1,"查询成功",json);
    }
}
